# -*- encoding : utf-8 -*-
#-------------------------------------
# Vinh
#-------------------------------------
class Admin::UserController < ApplicationController
  # specific layout
  layout 'admin/application'
  
  # list all users
  def index
    @users = User.paginate(:page => params[:page], :per_page => 10)
  end
  
  # create a new user
  def new
    @user = User.new
  end
  
  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "Create new reader successfully"
      # send notice email
      UserMailer.notice_create_account(@user, params[:user][:password]).deliver
      redirect_to :action => 'view', :id => @user.id
    else
      flash[:notice] = "There are some errors"
      render "new"
    end
  end
  
  # edit the information of user
  def edit
    @user = User.find(params[:id])
  end
  
  def update
    user = User.find(params[:id])
    if user.update_attributes(params[:user])
      redirect_to :controller => "admin/user", :action => "view", :id => user.id
    else
      render "edit"
    end
  end
  
  # view the information of user
  def view
    @user = User.find(params[:id])
  end
  
  # search user
  def search
    cate = params[:cate]
    keyword = params[:keyword]
    
    if params[:search]
      case cate.to_i
        when 0 then # ID
          @results_list = User.where('id = ?', keyword)
        when 1 then # Username
          @results_list = User.where('username LIKE ?', "%#{keyword}%")
        when 2 then # Card ID
          @results_list = User.where('card_id = ?', keyword)
        when 3 then # email
          @results_list = User.where('email LIKE ?', "%#{keyword}%")
        when 4 then # phone
          @results_list = User.where('phone LIKE ?', "%#{keyword}%")
        when 5 then # fullname
          @results_list = User.where('fullname LIKE ?', "%#{keyword}%")
      end
      @results_list = @results_list.paginate(:page => params[:page], :per_page => 3)
    end
  end
  
  # delete user
  def delete
    user = User.find(params[:id])
    user.destroy
    
    redirect_to :controller => "admin/user", :action => "index"
  end
  
  # session
  def login
    
  end
  
  def login_attempt
    authorized_user = User.authenticate(params[:username_or_email], params[:login_password])
    
    if(authorized_user)
      if authorized_user.role_id == 3
        session[:admin_user_id] = authorized_user.id
        redirect_to(:controller => 'admin/index', :action => 'index')
      else
        flash[:notice] = "Have not enough privilege!"
        render 'login'
      end
    else
      flash[:notice] = "Username or Password is incorrect!"
      render 'login'
    end
  end
  
  def logout
    session[:admin_user_id] = nil
    redirect_to :controller => 'admin/user', :action => 'login'
  end
end
